package com.cy.store.controller;

import com.cy.store.controller.ex.FileEmptyException;
import com.cy.store.controller.ex.FileSizeException;
import com.cy.store.controller.ex.FileTypeException;
import com.cy.store.controller.ex.FileUploadIOException;
import com.cy.store.entity.User;
import com.cy.store.service.IUserService;
import com.cy.store.service.ex.InsertException;
import com.cy.store.service.ex.UsernameDuplicatedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import util.JsonResult;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

//@Controller
@RestController
@RequestMapping("users")
public class UserController extends BaseController{
    @Autowired
    private IUserService userService;

    @RequestMapping("reg")
//    @ResponseBody//响应结果以json格式进行数据的响应给到前端
    public JsonResult<Void> reg(User user){
        userService.reg(user);
        return new JsonResult<>(Ok);
    }

    @RequestMapping("login")
    public JsonResult<User> login(String username , String password, HttpSession session){
        User data = userService.login(username,password);

        //向session对象中完成数据的绑定
        session.setAttribute("uid",data.getUid());
        session.setAttribute("username",data.getUsername());

        //小测试
        System.out.println(getUidFromSession(session));
        System.out.println(getUsernameFromSession(session));
        return new JsonResult<User>(Ok,data);
    }


    @RequestMapping("change_password")
    public JsonResult<Void> changePssword(String oldPassword,String newPassword,HttpSession session){
        Integer uid =  getUidFromSession(session);
        String username = getUsernameFromSession(session);
        userService.changePassword(uid,username,oldPassword,newPassword);
        return new JsonResult<>(Ok);
    }


    @RequestMapping("get_by_uid")
    public JsonResult<User> getByUid(HttpSession session){
        User us = userService.getByUid(getUidFromSession(session));
        return new JsonResult<>(Ok,us);

    }

    @RequestMapping("change_info")
    public  JsonResult<Void> changeInfo(User user,HttpSession session){
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        userService.changeInfo(uid,username,user);
        return new JsonResult<>(Ok);
    }

    /*设置上传文件最大值*/
    public static  final int AVATAR_MAX_SIZE = 10*1024*1024;

    /*限制上传文件的类型*/
    public static final List<String> AVATAR_TYPE  = new ArrayList<>();

    static {
        AVATAR_TYPE.add("image/jpeg");
        AVATAR_TYPE.add("image/png");
        AVATAR_TYPE.add("image/bmp");
        AVATAR_TYPE.add("image/gif");
    }

    @RequestMapping("change_avatar")
    public JsonResult<String> changeAvatar(HttpSession session, MultipartFile file){
        if(file.isEmpty()){
            throw new FileEmptyException("文件为空");
        }
        if(file.getSize() > AVATAR_MAX_SIZE){
            throw new FileSizeException("文件超出限制");
        }
        //判断文件类型是否符合
        String contentType = file.getContentType();
        if(!AVATAR_TYPE.contains(contentType)){
            throw new FileTypeException("文件类型不支持");
        }

        //上传的文件../upload/文件.png
        String parent = session.getServletContext().getRealPath("upload");
        //用file指向这个路径，判断路径是否存在
        File dir = new File(parent);

        if(!dir.exists()){
            dir.mkdir();//创建当前目录
        }

        //获取这个文件名称，用UUID工具来生成一个新的字符串作为文件名



        String originalFileName = file.getOriginalFilename();
        int index = originalFileName.lastIndexOf(".");
        String suffix = originalFileName.substring(index);
        String fileName = UUID.randomUUID().toString().toUpperCase()+suffix;
        File dest = new File(dir,fileName);//是一个空文件
        //将参数写入这个空文件中
        try {
            file.transferTo(dest);
        } catch (IOException e) {
           throw new FileUploadIOException("文件写入异常");
        }

        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);

        String avatar = "/upload/"+fileName;

        userService.changeAvatar(uid,avatar,username);

        //返回用户头像的路径给前端，用于头像展示
        return new JsonResult<>(Ok,avatar);


    }

}
